package org.sosie2.client.other;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringReader;

import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.client.AxisClient;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.configuration.NullProvider;
import org.apache.axis.message.SOAPBody;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.utils.XMLUtils;
import org.apache.log4j.Logger;
import org.sosie2.service.framework.Utils;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;


public class AdnClient
{
	public  static final String endPoint = "http://localhost:8080/axis/services/SOSIESimpleAnnotationWS?method=serve";
	//public  static final String endPoint = "http://localhost:8081/cucu";
	public  static final String request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + 
	"<m:serve \r\n" + 
	"xmlns:m=\"http://localhost:8080/axis/services/MyDestinationWS\">\r\n" + 
	"orange" + 
	"</m:serve>";
	
	public  static final String request2 = "<wfs:thisisMULE service=\"WFS\" version=\"1.0.0\" xmlns:wfs=\"http://www.opengis.net/wfs\">"+
		"UniBW"+"</wfs:thisisMULE>";
	
	static Logger logger = Logger.getLogger(WSClient.class);
	public static Message SOAPmessage;
	
	public static void initializeContext()
	{
		MessageContext msgContext;
		
		AxisClient tmpEngine = new AxisClient(new NullProvider());
		msgContext = new MessageContext(tmpEngine);
		InputStream in = new ByteArrayInputStream(Utils.emptySoapMsg.getBytes());
		Message msg = new Message(in);
		
		msg.setMessageContext(msgContext);	 
		
		StringReader strReader = new StringReader(request);		
		try{
			msg = Utils.addHeaderToHeaderlessMessage(new String[]{"m", "somename", "http://ws-i.org/schemas","ordner"}, msg);
			
			logger.info("Getting to the request...");
			Document document = XMLUtils.newDocument(new InputSource(strReader));
			
			// Add request to SOAP body
			SOAPBody body = (SOAPBody) msg.getSOAPBody();					
			body.addDocument(document);
			
			// SOAPBodyElement sbe = new SOAPBodyElement(new ByteArrayInputStream(contents.getBytes()));
			// body.addChildElement(sbe);
			
			Utils.dumpXML("SOAPMessage:", msg.getSOAPEnvelope().getAsDocument(),logger);
			
			SOAPmessage = msg;
		}
		catch(Exception e)
		{
			logger.warn("Exception : " + e.getMessage());
		}
	}
	
	public static void main(String args[])
	{
		initializeContext();
			
		try{
			Service  service = new Service();
	        Call call = (Call) service.createCall();
	        call.setTargetEndpointAddress( new java.net.URL(endPoint));
			
			System.out.println("Sent request to MyAdnWS web service..." );
			SOAPEnvelope response = (SOAPEnvelope)call.invoke(SOAPmessage);			
		}
		catch(Exception e)
		{
			logger.warn("Fault: " + e.getMessage());
			e.printStackTrace();
		}
	
	}
	
	
}


